/**
 * @file 学部看板报表
 * @author ruanairuo(ruanairuo@baijia.com)
 * @date 2020-03-18
 */
import React, {useEffect, useState, useRef} from 'react';
import {Card, Row, Col} from 'antd';
import CommonSearchBar from '~/page/FineBi/common/CommonSearchBar';
import {querySelectOptions} from '~/service/refundReport';
import {convertSearcherParams, toLine} from '~/page/FineBi/utils/convert';
import {userRoundIdx, initUserRoundIdx} from '~/utils/const';
import BarChart from '../BarChart';
import BarStackChart from '../BarStackChart';

import {getDefaultDimension, searchConfig, initialValues} from './config';

const SELECT_UNIT_ID = 'DepartmentDimensionReport_PartSix_select';
const dIdPre = 'DepartmentDimensionReport_PartSix_select';

const departmentName = 'department';

export default function ContinuousTerm(props) {
    const initDemenstion = (getDefaultDimension(SELECT_UNIT_ID))
        .concat(props.initPropDimensionAndValues);
    const [selectOptions, setSelectOptions] = useState({});
    // 共同查询条件
    const [dimensionAndValues, setDimensionAndValues] = useState(initDemenstion);
    const [isSearch, setIsSearch] = useState(false);
    const [defaultDepartment, setDefaultDepartment] = useState([]);
    const formRef = useRef();

    useEffect(() => {
        const findItem = initDemenstion.find(item => item.dimensionName === userRoundIdx);
        findItem.value = [props.userRoundValue];
        const findDepartment = initDemenstion.find(item => item.dimensionName === departmentName);
        findDepartment.value = [defaultDepartment];

        setDimensionAndValues([...initDemenstion]);

        formRef.current.formFields.resetFields();
        formRef.current.formFields.setFieldsValue({
            department: [defaultDepartment]
        });
    }, [props.userRoundValue]);

    const handleOk = fieldsValue => {
        const params = convertSearcherParams(fieldsValue);
        setDimensionAndValues([...params, {...props.initPropDimensionAndValues[0], value: [props.userRoundValue]}]);
    };

    const handleReset = e => {
        const findItem = initDemenstion.find(item => item.dimensionName === userRoundIdx);
        findItem.value = [props.userRoundValue];
        const findDepartment = initDemenstion.find(item => item.dimensionName === departmentName);
        findDepartment.value = [defaultDepartment];
        setDimensionAndValues([...initDemenstion]);
        formRef.current.formFields.setFieldsValue({
            department: [defaultDepartment]
        });
    };

    // 选项查询
    const handleFetchOptions = (options, defaultKey) => {
        const {key, searchKey, pager, isGetingMore, options: curOptions, fieldsValue = []} = options;
        let permissions = searchConfig.map(item => ({
            dimensionId: `${dIdPre}_${toLine(item.key)}`,
            dimensionName: toLine(item.key),
            filterItems: Array.isArray(fieldsValue[item.key])
                ? fieldsValue[item.key]
                : fieldsValue[item.key] == null
                    ? []
                    : [fieldsValue[item.key]]
        }));

        permissions = permissions.filter(item => (item.filterItems?.length && item.dimensionName !== userRoundIdx));
        permissions.push({...props.initPropDimensionAndValues[0], value: [props.userRoundValue]});

        const params = {
            pager,
            dimensionId: `${dIdPre}_${toLine(key)}`,
            dimensionName: toLine(key),
            searchKey,
            permissions,
            unitId: SELECT_UNIT_ID
        };

        querySelectOptions(params).then(res => {
            const {data = [], pager} = res;
            if (defaultKey) {
                if (data?.length > 0) {
                    setDefaultDepartment(data[0]);
                }
                formRef.current.formFields.setFieldsValue({
                    [defaultKey]: data?.length > 0 ? [data[0]] : []
                });
                let dimension = [...dimensionAndValues];
                if (!dimension.length) {
                    dimension = getDefaultDimension(dIdPre);
                }
                const defaultKeyIndex = dimension.findIndex(ele => ele.dimensionName === defaultKey);
                if (defaultKeyIndex > -1) {
                    dimension[defaultKeyIndex].value = data?.length > 0 ? [data[0]] : [];
                }
                setDimensionAndValues(dimension);
                setIsSearch(true);
            }
            let options =
                data.map(item => ({
                    key: item,
                    value: item,
                    label: item
                })) || [];
            // 分页时，累加展示
            if (isGetingMore) {
                options = curOptions.concat(options);
            }
            setSelectOptions({key, options, pager});
        });
    };
    // 表单change
    const handleItemChange = itemKeyValue => {
        const filterValue = {...itemKeyValue};
        for (const i in filterValue) {
            filterValue[i] = Array.isArray(filterValue[i])
                ? filterValue[i].filter(ele => ele !== '全部') : [filterValue[i]];
            formRef.current.formFields.setFieldsValue({
                [i]: filterValue[i]
            });
        }
    };
    useEffect(() => {
        handleFetchOptions({key: searchConfig[0].key}, searchConfig[0].key);
    }, []);
    return (
        <div>
            <Card style={{marginBottom: 8}}>
                <CommonSearchBar
                    noCache
                    config={searchConfig}
                    initialValues={initialValues}
                    onOk={handleOk}
                    onReset={handleReset}
                    onfetchOptions={handleFetchOptions}
                    selectOptions={selectOptions}
                    ref={formRef}
                    onItemChange={handleItemChange}
                />
            </Card>
            <Card>
                <Row>
                    <Col span={12}>
                        <BarChart
                            dId="DepartmentDimensionReport_PartSix"
                            unitId="DepartmentDimensionReport_PartSix_composite"
                            selectId={SELECT_UNIT_ID}
                            dimensionAndValues={dimensionAndValues}
                            isSearch={isSearch}
                            requestUrl="renewRate"
                            height={430}
                        />
                    </Col>
                    <Col span={12}>
                        <BarStackChart
                            dId="DepartmentDimensionReport_PartSeven"
                            unitId="DepartmentDimensionReport_PartSeven_composite"
                            selectId={SELECT_UNIT_ID}
                            dimensionAndValues={dimensionAndValues}
                            tableId="DepartmentDimensionReport_PartSeven_excel"
                            isSearch={isSearch}
                            requestUrl="renewPerson"
                        />
                    </Col>
                    <Col span={12}>
                        <BarChart
                            dId="DepartmentDimensionReport_PartEight"
                            unitId="DepartmentDimensionReport_PartEight_composite"
                            selectId={SELECT_UNIT_ID}
                            dimensionAndValues={dimensionAndValues}
                            isSearch={isSearch}
                            requestUrl="renewRate"
                            height={430}
                        />
                    </Col>
                    <Col span={12}>
                        <BarStackChart
                            dId="DepartmentDimensionReport_PartNine"
                            unitId="DepartmentDimensionReport_PartNine_composite"
                            selectId={SELECT_UNIT_ID}
                            dimensionAndValues={dimensionAndValues}
                            tableId="DepartmentDimensionReport_PartNine_excel"
                            isSearch={isSearch}
                            requestUrl="percentRate"
                        />
                    </Col>
                </Row>
            </Card>
        </div>
    );
}
